package com.hrz.lib.rxmvpdemo2.contract.main;

import com.hrz.lib.rxmvpdemo2.NetApi;
import com.hrz.lib.rxmvpdemo2.NewResponse;
import com.hrz.lib.rxmvpdemo2.bean.NewsBean;
import com.rxmvp.baselibrary.App;
import com.rxmvp.baselibrary.base.RxBasePresenter;
import com.rxmvp.baselibrary.base.RxHelper;
import com.rxmvp.baselibrary.base.mvp.IBaseView;
import com.rxmvp.baselibrary.rxbus.Events;
import com.rxmvp.baselibrary.rxbus.RxBus;
import com.rxmvp.baselibrary.rxretrofit.subscriber.ResponseSubscriber;
import com.rxmvp.baselibrary.utils.LogUtil;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * MainActivity的presenter，负责处理MainActivity的业务逻辑，减轻MainActivity的代码量，也起到与界面交互解耦的作用，方便单元测试
 * <p>
 * 作者： huangRZ on 2017/1/21. 15:04
 * 邮箱：917647409@qq.com
 */
public class MainPresenter extends RxBasePresenter<MainContract.IView, ActivityEvent> implements MainContract.IPresenter {

    private NetApi api;
    private Disposable mDisposable;
    private Disposable mDisposable2;

    //提供MainPresenter的实例，其参数的实例由注入到MainActivity的component管理的module提供
    @Inject
    public MainPresenter(IBaseView view, LifecycleProvider<ActivityEvent> activityLifecycleProvider,
                         RxHelper<ActivityEvent> rxUtils, NetApi api) {
        super(view, activityLifecycleProvider, rxUtils);
        this.api = api;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onStart() {
        if (mDisposable2 == null) {
            mDisposable2 = RxBus.with(mLifecycleProvider)
                    .setEvent(Events.TAP)
                    .setLifecycleEvent(ActivityEvent.DESTROY)
                    .onError(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            /**
                             * 笔记： 如果有异常发生，那么subscriber就会自动取消订阅，不再观察到事件的发生
                             */
                            LogUtil.e(throwable.getMessage());
                            //将disposable置为null，下次进入界面重新开始订阅
                            mDisposable2 = null;
                        }
                    })
                    .onNext(new Consumer<Events<?>>() {
                        @Override
                        public void accept(Events<?> events) throws Exception {
                            String text = (String) events.getContent();
                            LogUtil.e("response : " + text);
                            mView.setText(text);
                        }
                    })._create();
        }
    }

    @Override
    public void onStop() {

    }

    public void loadData() {
        mDisposable = mRxHelper
                .setLifecycleEvent(ActivityEvent.DESTROY) //设置subscriber在Activity销毁时自动解绑
                .getFlowable(api.getJson("top", "004a2b29ab3245fdfb95ed25e590cc2b"), mLifecycleProvider)
                .subscribeWith(new ResponseSubscriber<NewResponse<NewsBean>>() {
                    @Override
                    public void onSuccess(NewResponse<NewsBean> response) {
                        if (response != null) {
                            Events<String> stringEvents = new Events<>();
                            stringEvents.setCode(Events.TAP);
                            stringEvents.setContent(response.getResult().getData().get(0).toString());
                            RxBus.getInstance().send(stringEvents);
                        }
                    }

                    @Override
                    protected void onStart() {
                        super.onStart();
                        mView.showPB();
                    }

                    @Override
                    public void onFailure() {
                        super.onFailure();
                        mView.hidePB();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mView.hidePB();
                    }
                });

        App.getRefWatcher(App.getApp()).watch(mDisposable);
    }

    //取消所有订阅了的subscriber，避免内存泄漏
    @Override
    public void cancelSubscription() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
            if (mView != null) {
                mView.hidePB();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelSubscription();
        if (mDisposable2 != null){
            mDisposable2 = null;
        }
    }

}
